package com.kaola.gulimall.product.exception;

import com.kaola.common.exception.BizCodeEnume;
import com.kaola.common.utils.R;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: 类名 MallExceptionControllerAdvice
 * @Description: TODO(集中处理异常)
 * @Author: zhang-hairong
 * @Date 2021-10-27 17:46
 */

@Slf4j
@ResponseBody
@RestControllerAdvice(basePackages = "com.kaola.gulimall.product.controller")
public class MallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) ->{
            map.put(item.getField(), item.getDefaultMessage());
        });
        log.error("数据校验出现问题{}, 异常类型: {}", e.getMessage(), e.getClass());
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("错误", throwable);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
